package com.hn.springcloud.controller;

import com.hn.springcloud.pojo.User;
import com.hn.springcloud.vo.ResponseVo;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * hanni
 * 2019/2/13 0013
 * 8:38
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private DiscoveryClient client;

    Logger logger = LoggerFactory.getLogger(getClass());
    @GetMapping
    public User findUser(){

        logger.error("调用到了provider");
        return new User(1,serverPort);
    }

    @GetMapping("/servers")
    public String servers(){
        List<String> list = client.getServices();
        for (String s : list) {
            System.out.println(s);
            List<ServiceInstance> instances = client.getInstances(s);
            for (ServiceInstance instance : instances) {
                System.out.println( instance.getHost()+","+instance.getPort());
            }
        }
        return "ok";
    }
    //采用Rest请求
    @PostMapping()
    @ApiOperation(value = "添加用户",httpMethod = "POST")
    @ApiImplicitParams(@ApiImplicitParam(name="u",value = "这个是用户信息"))
    @ApiResponses(
            value = {
                    @ApiResponse(code=200,message = "成功"),
                    @ApiResponse(code = 500, message = "内部错误")
            }
    )
    public ResponseVo add(@RequestBody User user){

        try{
            System.out.println(user);
            return ResponseVo.ok("添加成功");
        }catch (Exception e){

            return ResponseVo.error("添加失败");
        }
    }

    @PostMapping("/a")
    public ResponseVo add(Integer id,String name){

        try{
            System.out.println(id+","+ name);
            return ResponseVo.ok("添加成功");
        }catch (Exception e){

            return ResponseVo.error("添加失败");
        }
    }

    @GetMapping("/b")
    public List<User> get() {

        return Arrays.asList(new User(6, "张三"), new User(7, "李四"));
    }

    @GetMapping("/c")
    public List<User> get(@RequestBody User user) {

        System.out.println(user);
        return Arrays.asList(new User(6, "张三"), new User(7, "李四"));
    }

    @GetMapping("/d")
    public List<User> get(Integer id,String name) {

        System.out.println(id+","+name);
        return Arrays.asList(new User(6, "张三"), new User(7, "李四"));
    }

    //占位符传参
    @DeleteMapping("/e/{id}/xxx/{name}")
    public ResponseVo delete(@PathVariable("id") Integer uid,@PathVariable("name")String uname){
        System.out.println(uid+","+uname);
        return ResponseVo.ok("删除成功");
    }


}
